package com.lingnan.util;

/**
 * @Author 梁兴达
 * @Date 2022/3/22 0:11:57
 * @Version 1.0
 */
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import com.qiniu.util.Auth;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DownLoadQiNiu {
    String accessKey = "d-prL59zWGXHSMpnxl792FdjFOV9qhSyVRmAVlzv";          //AccessKey值
    String secretKey = "n9TjF-SBqQfZjE9ISCHweKF_E9rKG0qZUTlkUw5b";          //SecretKey值
    //密钥配置
    Auth auth = Auth.create(accessKey,secretKey);
    /**
     * 获取下载文件路径，即：donwloadUrl
     */
    public String getDownloadUrl(String targetUrl) {
        String downloadUrl = auth.privateDownloadUrl(targetUrl);
        return downloadUrl;
    }
    /**
     * 下载
     */
    public void download(String targetUrl) {
        //获取downloadUrl
        String downloadUrl = getDownloadUrl(targetUrl);
        //本地保存路径
        String filePath = "C:\\Users\\84846\\Desktop\\rili-upload";
        download(downloadUrl, filePath);
    }
    /**
     * 通过发送http get 请求获取文件资源
     */
    private static void download(String url, String filepath) {
        OkHttpClient client = new OkHttpClient();
        System.out.println(url);
        Request req = new Request.Builder().url(url).build();
        Response resp = null;
        try {
            resp = client.newCall(req).execute();
            System.out.println(resp.isSuccessful());
            if(resp.isSuccessful()) {
                ResponseBody body = resp.body();
                InputStream is = body.byteStream();
                byte[] data = readInputStream(is);
                File imgFile = new File(filepath);   //下载到本地的图片命名
                FileOutputStream fops = new FileOutputStream(imgFile);
                fops.write(data);
                fops.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Unexpected code " + resp);
        }
    }
    /**
     * 读取字节输入流内容
     */
    private static byte[] readInputStream(InputStream is) {
        ByteArrayOutputStream writer = new ByteArrayOutputStream();
        byte[] buff = new byte[1024 * 2];
        int len = 0;
        try {
            while((len = is.read(buff)) != -1) {
                writer.write(buff, 0, len);
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return writer.toByteArray();
    }

}

